<template>
  <el-upload
    class="avatar-uploader"
    :headers="importHeaders"
    :action="action"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload">
    <img v-if="imgUrl" :src="imgUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>

<script>
import uploadDefault from '@/assets/upload-default.png'
import { getToken } from '@/utils/auth'

export default {
  name: 'UploadImage',
  props: ['value', 'pathPrefix', 'uploadUrl'],
  data() {
    return {
      uploadDefault,
      imgUrl: this.value,
      importHeaders: {
        token: getToken()
      }
    }
  },
  computed: {
    action() {
      return this.uploadUrl ? process.env.VUE_APP_BASE_API +  this.uploadUrl : `${process.env.VUE_APP_BASE_API}/platform/file/upload/images/${this.pathPrefix || ''}`
    }
  },
  watch: {
    value(value){
      if (!this.imgUrl) {
        this.imgUrl = value;
      }
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      if (res.code == 200) {
        this.imgUrl = res.data.url
        this.$emit('input', `${res.data.key}`);
      }
    },
    beforeAvatarUpload() {
      return true;
    }
  }
}
</script>

<style lang="scss">
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>